// 返回顶部，自带效果
function backToTop(){
    let scrollToTop

    if (window.getComputedStyle && window.getComputedStyle(document.body).scrollBehavior) {
        scrollToTop = () => document.querySelector('body')
            .scrollIntoView({
                behavior: 'smooth',
                block: 'start',
            })
    } else {
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (callback) {
                return setTimeout(callback, 1000 / 60)
            }
        }

        scrollToTop = () => {
            const c = document.documentElement.scrollTop || document.body.scrollTop
            if (c > 0) {
                window.requestAnimationFrame(scrollToTop)
                window.scrollTo(0, c - c / 8)
            }
        }
    }
    scrollToTop()
}

//可拖放元素
function drap(id) {
    var div2 = document.getElementById(id);
    var flag = false;
    var cur = {
        x: 0,
        y: 0
    }
    var nx, ny, dx, dy, x, y;
    function down() {
        flag = true;
        var touch;
        if (event.touches) {
            touch = event.touches[0];
        } else {
            touch = event;
        }
        cur.x = touch.clientX;
        cur.y = touch.clientY;
        dx = div2.offsetLeft;
        dy = div2.offsetTop;
    }
    function move(e) {
        e.preventDefault();
        if (flag) {
            var touch;
            if (event.touches) {
                touch = event.touches[0];
            } else {
                touch = event;
            }
            nx = touch.clientX - cur.x;
            ny = touch.clientY - cur.y;
            x = dx + nx;
            y = dy + ny;
            div2.style.left = x + "px";
            div2.style.top = y + "px";
            //阻止页面的滑动默认事件
            // document.addEventListener("touchmove",function(){
            //     event.preventDefault();
            // },false);
        }
    }
    //鼠标释放时候的函数
    function end() {
        flag = false;
    }
    div2.addEventListener("mousedown", function (e) {
        down(e);
    }, false);
    div2.addEventListener("touchstart", function (e) {
        down(e);
    }, false)
    div2.addEventListener("mousemove", function (e) {
        move(e);
    }, false);
    div2.addEventListener("touchmove", function (e) {
        move(e);
    }, false)
    document.body.addEventListener("mouseup", function (e) {
        end(e);
    }, false);
    div2.addEventListener("touchend", function (e) {
        end(e);
    }, false);
}

// 返回页面顶部
export function backToTopNow() {
    window.pageYOffset = 0
    document.documentElement.scrollTop = 0
    document.body.scrollTop = 0
}

// 回到页面底部
export const topPageBottom = () => {
    document.documentElement.scrollTop = document.body.scrollHeight || document.documentElement.scrollHeight
}

export { backToTop, drap }